package com.xfunc.utils;

import android.app.Activity;
import android.app.Application;
import android.os.Bundle;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * App config 可见性状态监听
 */
public class AppVisibleManager {
    private int     mForegroundCount = 0;
    private int     mConfigCount     = 0;
    private boolean mIsBackground    = false;
    private AppVisibleManager() {
    }

    public static AppVisibleManager getInstance() {
        return AppStatusClassHolder.instance;
    }

    private static class AppStatusClassHolder {
        private static final AppVisibleManager instance = new AppVisibleManager();
    }
    public boolean isAppForeground() {
        return !mIsBackground;
    }
    private final LinkedList<Activity> mActivityList = new LinkedList<>();

   public void init(Application app) {
       Log.d("Lifecycle-App:::","APP前后台状态监听 初始化");
        app.registerActivityLifecycleCallbacks(new Application.ActivityLifecycleCallbacks() {
            @Override
            public void onActivityCreated(@NonNull Activity activity, @Nullable Bundle savedInstanceState) {
                if (mActivityList.size() == 0) {
                    postStatus(activity, true);
                }
            }

            @Override
            public void onActivityStarted(@NonNull Activity activity) {
                if (!mIsBackground) {
                    setTopActivity(activity);
                }
                if (mConfigCount < 0) {
                    ++mConfigCount;
                } else {
                    ++mForegroundCount;
                }
            }

            @Override
            public void onActivityResumed(@NonNull Activity activity) {
                Log.d("生命周期：：：","Lifecycle-App- 可见：" +activity.getClass().getSimpleName());
                setTopActivity(activity);
                if (mIsBackground) {
                    mIsBackground = false;
                    postStatus(activity, true);
                }
            }

            @Override
            public void onActivityPaused(@NonNull Activity activity) {
                Log.d("生命周期：：：","Lifecycle-App- 不可见：" +activity.getClass().getSimpleName());
            }

            @Override
            public void onActivityStopped(@NonNull Activity activity) {
                if (activity.isChangingConfigurations()) {
                    --mConfigCount;
                } else {
                    --mForegroundCount;
                    if (mForegroundCount <= 0) {
                        mIsBackground = true;
                        postStatus(activity, false);
                    }
                }
            }

            @Override
            public void onActivitySaveInstanceState(@NonNull Activity activity, @NonNull Bundle outState) {

            }

            @Override
            public void onActivityDestroyed(@NonNull Activity activity) {
                Log.d("生命周期：：：","Lifecycle-App- 销毁：" +activity.getClass().getSimpleName());
                mActivityList.remove(activity);
                if(mActivityList.isEmpty()){
                    Log.d("生命周期：：：","警告⚠️⚠️⚠️⚠️⚠️⚠️⚠️【 所有Activity 都没有了，应该清除 Application 相关进程 以及主进程 】");
                    AppProcessUtils.killAppProcess();
                }
            }
        });
    }

    private final List<OnAppStatusChangedListener> mStatusListeners  = new CopyOnWriteArrayList<>();

    void addOnAppStatusChangedListener(final OnAppStatusChangedListener listener) {
        mStatusListeners.add(listener);
    }

    void removeOnAppStatusChangedListener(final OnAppStatusChangedListener listener) {
        mStatusListeners.remove(listener);
    }
    void onForeground(Activity activity){
        Log.d("生命周期：：：","Lifecycle-App- 在前台：" +activity.getClass().getSimpleName());
    }
    void onBackground(Activity activity){
        Log.d("生命周期：：：","Lifecycle-App 在后台："+activity.getClass().getSimpleName());
    }

    private void postStatus(final Activity activity, final boolean isForeground) {
        if (isForeground) {
            onForeground(activity);
        } else {
            onBackground(activity);
        }
        if (mStatusListeners.isEmpty()) return;
        for (OnAppStatusChangedListener statusListener : mStatusListeners) {
            if (isForeground) {
                statusListener.onForeground(activity);
            } else {
                statusListener.onBackground(activity);
            }
        }
    }
    private void setTopActivity(final Activity activity) {
        if (mActivityList.contains(activity)) {
            if (!mActivityList.getFirst().equals(activity)) {
                mActivityList.remove(activity);
                mActivityList.addFirst(activity);
            }
        } else {
            mActivityList.addFirst(activity);
        }
    }
    public interface OnAppStatusChangedListener {

        void onForeground(Activity activity);

        void onBackground(Activity activity);
    }
}
